//index.js
// 用户，商家，菜单，订单，子订单，支付，搜索，评价
var app = getApp()
var util = require('../../utils/util.js');
var cartjs = require('../../utils/shopcat.js')
Page({
  data: {
    // index
    userInfo: {},

    // order
    orderOk: false,
    // me
    img: '',
    orders: [{
      "id": 10,
      "orderNo": "191027S4009",
      "weiuser": 5,
      "username": "陈振选",
      "shopname": "321",
      "sellerphone": "1112",
      "subOrders": [{
        "name": "五花肉石锅拌饭",
        "price": "51",
        "num": 4,
        "amonut": "204"
      }],
      "amount": "0",
      "oamount": "0",
      "payamount": "0",
      "state": 0,
      "createTime": "2019-10-27 02:34:34",
      "fetchTime": "现在,10：34",
      "paytype": 0,
      "paystate": 0
    }],
    pagenum: 0,
    pagesize: 10,
    hasnextpage: false,

    currentTab: -1,
    orderstate: '-1',

    oid: 0,
    amount: 0,
    date:'',
    yearmonth:[[2019],[1,2,3,4,5,6,7,8,9,10,11,12]],
    yearindex:0,
    monthindex:0
  },
  onLoad: function() {
    var date = new Date();
    var year = date.getFullYear();
    
    
    var years=[2019]
    while (year - years[years.length-1]>0){
      years.push(year);
    }
    var yearmonth = this.data.yearmonth;
    yearmonth[0] = years;
    this.setData({
      yearmonth: yearmonth
    })
    this.getOrderYearMonth(year, date.getMonth()+1);
  },
  onShow: function() { 
    //this.setOrder();
    var redpackage = wx.getStorageSync("redpackage");
    var oid=this.data.oid;
    if (redpackage && redpackage.id && oid > 0) {
      var dis = 0;
      var amount = this.data.amount
      if (redpackage.redtype == 0) {
        var discount = redpackage.discount;
        if (discount && discount != 0) {
          dis = (100 - discount) / 100 * amount;
        }
      } else if (redpackage.redtype == 1) {
        var reduction = redpackage.reduction;
        reduction.sort(function(a, b) {
          return b.full - a.full;
        })
        for (var i = reduction.length - 1; i >= 0; i--) {
          if (amount >= reduction[i].full * 100) {
            dis = reduction[i].reduce * 100;
            continue;
          }
        }

      }
      dis = dis.toFixed(0);
      var orders = this.data.orders;
      var redpak = {
        id: redpackage.id,
        disamount: dis,
        title: redpackage.title
      };

      for (var i = 0; i < orders.length; i++) {
        if (orders[i].state == 0 && orders[i].id == oid) {
          orders[i].redpackage = redpak;
          orders[i].disamount = orders[i].redpackage.disamount;
          orders[i].payamount = orders[i].amount - orders[i].redpackage.disamount
        }
      }
      this.setData({ orders: orders})
    }

  },
  setOrder: function(startTime,endTime) {
    var url = util.url.order_history;
    if (startTime) url += "?startTime=" + startTime;
    if (endTime) url += "&endTime="+endTime;
    var that = this
    util.fetchGet(
      url,
      function(ret) {
        var list = ret.data;
       // if (list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            var fetchTime = list[i].fetchTime;
            list[i].fetchTime = fetchTime.substring(5, fetchTime.length);
            if (list[i].state == 0) {
              
              list[i].payamount = list[i].amount;
              list[i].disamount = 0;           
            }
            if (list[i].createTime){
              var date = new Date(list[i].createTime);
              list[i].createTime = util.getNextTime(0, date);
            }
          }
          that.setData({
            orders: list
          })
       // }
      }
    )
  },
  // order
  orderOk: function() {
    this.setData({
      orderOk: true
    })
  },
  okCancel: function() {
    this.setData({
      orderOk: false
    })
  },
  calling: function() {
    wx.makePhoneCall({
      phoneNumber: '18316588252',
      success: function() {
        console.log("拨打电话成功！")
      },
      fail: function() {
        console.log("拨打电话失败！")
      }
    })
  },
  okOk: function() {
    this.setData({
      orderOk: false
    })
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  payorder: function(e) {
    var that = this;
    var url = util.url.order_pay;
    url += "?id=" + e.currentTarget.dataset.id;
    util.fetchGet(
      url,
      function(data) {
        that.testSubmitOrder(data.data);
      }
    )
  },
  anotherOrder: function(e) {
    var that = this;
    var url = util.url.order_copy;
    url += "?id=" + e.currentTarget.dataset.id;
    util.fetchGet(
      url,
      function(data) {
        var suborders = data.data;
        var carts = [];
        var tnum = 0;
        for (var i = 0; i < suborders.length; i++) {

          suborders[i].selected = true;
          carts.push(suborders[i]);

          tnum += suborders[i].num;
        }
        cartjs.setcartlist(carts);
        //wx.setStorageSync("cartsto",carts);
        //cartjs.setTabBadge(1,tnum);
        //console.log(data);
        wx.navigateTo({
          url: '/pages/submitOrder/submitOrder',
        })
      }
    )
  },
  testSubmitOrder: function(data) {
    var url = 'pay/testnotify';
    url += "?out_trade_no=" + data.outTradeNo
    util.fetchGet(
      url,
      function(ret) {
        console.log(ret);
      }
    )
  },
  swichNav: function(e) {
    console.log(e);
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
        orderstate: e.target.dataset.current
      })
    }
  },
  toChoosePackage: function(e) {
    var oid = e.currentTarget.dataset.id;
    var amount = e.currentTarget.dataset.amount;
    this.setData({
      oid: oid,
      amount: amount
    })
    wx.navigateTo({
      url: '../myPackage/myPackage?amount=' + amount + "&oid=" + oid,
    })
  },
  bindcolumnchange:function(e){
    /*var yearmonth = this.data.yearmonth;
    var column=e.detail.column;
    var value = e.detail.value;
    var now = new Date();
    var nowyear = now.getFullYear()
    var nowmonth = now.getMonth();
    var year = yearmonth[0]
    if (column==0){
      if (nowyear == year[value]){
        var mons=[];
        for (var i = 1; i <= nowmonth;i++){
          mons.push(i);
        }
        yearmonth[1] = mons;
      }else{
        var mons = [];
        for (var i = 1; i <= 12; i++) {
          mons.push(i);
        }
        yearmonth[1] = mons;
      }
    }    
    this.setData({ yearmonth: yearmonth})*/
  },
  bindChange:function(e){
    var value= e.detail.value;
    var yearmonth = this.data.yearmonth;
    this.setData({
      yearindex:value[0],
      monthindex:value[1]
    })
    var month = yearmonth[1][value[1]];
    var year = yearmonth[0][value[0]];
    this.getOrderYearMonth(year,month);
  },
  getOrderYearMonth:function(year,month){

    var day = 30;
    if (month in [1, 3, 5, 7, 8, 10, 12]) {
      day = 31
    } else if (month in [4, 6, 9, 11]) {
      day = 30
    } else {
      if (year % 4 == 0) {
        day = 29;
      } else {
        day = 28;
      }
    }
    if (month < 10) month = "0" + month;
    var endTime = year + "-" + month + "-" + day + " 23:59:59"
    var startTime = year + "-" + month + "-" + "01" + " 00:00:00"
    this.setData({
      date: year + "-" + month
    })
    this.setOrder(startTime, endTime, util.url.order_history);
  },
  bindOrderdetail:function(e){
    var oid=e.currentTarget.dataset.oid;
    wx.navigateTo({
      url: '../orderDetail/orderDetail',
    })
  },
  
})